import React, { useState, useEffect, useCallback } from 'react';
import {
  Space,
  Typography,
  Card,
  Button,
  Progress,
  Input
} from 'tdesign-react';
import { PlayIcon, PauseIcon, RefreshIcon, StarIcon, HeartIcon, GiftIcon } from 'tdesign-icons-react';
import AnimatedCharacter from '../effects/AnimatedCharacter';
import { useSound } from '../../hooks/useSound';
import { themeColors, spacing, borderRadius } from '../../theme/theme';

const { Text, Title } = Typography;

interface TypingGameProps {
  onScoreUpdate?: (score: number) => void;
}

// 适合6-7岁儿童的简单词汇
const KIDS_WORDS = [
  '猫', '狗', '鱼', '鸟', '花',
  '树', '太阳', '月亮', '星星', '水',
  '火', '山', '海', '天', '地',
  '爸爸', '妈妈', '我', '你', '他',
  '红', '蓝', '黄', '绿', '白',
  '大', '小', '高', '矮', '好',
  '车', '船', '飞机', '房子', '学校',
  '书', '笔', '纸', '桌子', '椅子'
];

const TypingGame: React.FC<TypingGameProps> = ({ onScoreUpdate }) => {
  const [currentWord, setCurrentWord] = useState('');
  const [userInput, setUserInput] = useState('');
  const [score, setScore] = useState(0);
  const [streak, setStreak] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [timeLeft, setTimeLeft] = useState(60);
  const [feedback, setFeedback] = useState<'correct' | 'error' | null>(null);
  const [level, setLevel] = useState(1);
  const [characterMood, setCharacterMood] = useState<'happy' | 'sad' | 'dancing' | 'sleeping' | 'normal'>('normal');
  
  const { playSuccessSound, playErrorSound, playClickSound, playLevelUpSound } = useSound();

  const getRandomWord = useCallback(() => {
    const randomIndex = Math.floor(Math.random() * KIDS_WORDS.length);
    return KIDS_WORDS[randomIndex];
  }, []);

  const startNewWord = useCallback(() => {
    setCurrentWord(getRandomWord());
    setUserInput('');
    setFeedback(null);
  }, [getRandomWord]);

  const startGame = () => {
    playClickSound();
    setIsPlaying(true);
    setTimeLeft(60);
    setScore(0);
    setStreak(0);
    setLevel(1);
    setCharacterMood('normal');
    startNewWord();
  };

  const pauseGame = () => {
    setIsPlaying(false);
  };

  const resetGame = () => {
    setIsPlaying(false);
    setTimeLeft(60);
    setScore(0);
    setStreak(0);
    setLevel(1);
    setUserInput('');
    setCurrentWord('');
    setFeedback(null);
  };

  useEffect(() => {
    if (isPlaying && timeLeft > 0) {
      const timer = setTimeout(() => {
        setTimeLeft(timeLeft - 1);
      }, 1000);
      return () => clearTimeout(timer);
    } else if (timeLeft === 0) {
      setIsPlaying(false);
    }
  }, [isPlaying, timeLeft]);

  useEffect(() => {
    if (onScoreUpdate) {
      onScoreUpdate(score);
    }
  }, [score, onScoreUpdate]);

  const handleInputChange = (value: string) => {
    if (!isPlaying) return;
    
    setUserInput(value);

    if (value === currentWord) {
      setFeedback('correct');
      setCharacterMood('happy');
      playSuccessSound();
      
      const newScore = score + (10 * level) + (streak * 2);
      setScore(newScore);
      setStreak(streak + 1);
      
      // 升级逻辑
      if (streak > 0 && (streak + 1) % 5 === 0) {
        const newLevel = level + 1;
        setLevel(newLevel);
        setCharacterMood('dancing');
        playLevelUpSound();
      }
      
      setTimeout(() => {
        setCharacterMood('normal');
        startNewWord();
      }, 1000);
    } else if (currentWord.startsWith(value)) {
      setFeedback(null);
      setCharacterMood('normal');
    } else if (value.length > 0) {
      setFeedback('error');
      setCharacterMood('sad');
      playErrorSound();
      setStreak(0);
      setTimeout(() => {
        setFeedback(null);
        setCharacterMood('normal');
        setUserInput('');
      }, 800);
    }
  };

  const progress = ((60 - timeLeft) / 60) * 100;

  const gameContainerStyle: React.CSSProperties = {
    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    borderRadius: borderRadius.large,
    padding: spacing.xl,
    minHeight: '80vh',
    position: 'relative',
    overflow: 'hidden',
    maxWidth: '800px',
    margin: '0 auto'
  };

  const wordDisplayStyle: React.CSSProperties = {
    fontSize: '2.5rem',
    fontWeight: 'bold',
    textAlign: 'center',
    padding: spacing.xl,
    backgroundColor: feedback === 'correct' ? themeColors.success : feedback === 'error' ? themeColors.error : '#fff',
    color: feedback === 'correct' ? '#fff' : feedback === 'error' ? '#fff' : '#333',
    borderRadius: borderRadius.large,
    margin: `${spacing.m} 0`,
    minHeight: '100px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    transition: 'all 0.3s ease',
    letterSpacing: '0.1em',
    fontFamily: '"Comic Sans MS", cursive, sans-serif',
    animation: feedback === 'correct' ? 'bounce 0.6s' : feedback === 'error' ? 'shake 0.5s' : 'none'
  };

  const typingInputStyle: React.CSSProperties = {
    fontSize: '2rem',
    textAlign: 'center',
    fontFamily: '"Comic Sans MS", cursive, sans-serif',
    border: `3px solid ${themeColors.warning}`,
    borderRadius: borderRadius.large
  };

  const scoreCardStyle: React.CSSProperties = {
    background: `linear-gradient(45deg, ${themeColors.warning} 30%, ${themeColors.primary} 90%)`,
    borderRadius: borderRadius.large,
    color: '#fff',
    margin: spacing.xs,
    minWidth: '120px'
  };

  return (
    <div style={gameContainerStyle}>
      {/* 背景图案 */}
      <div style={{
        position: 'absolute',
        top: '-50%',
        left: '-50%',
        width: '200%',
        height: '200%',
        background: `
          radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px),
          radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px)
        `,
        backgroundSize: '20px 20px',
        backgroundPosition: '0 0, 10px 10px',
        animation: 'float 20s infinite linear',
        pointerEvents: 'none',
      }} />

      <div style={{ textAlign: 'center', marginBottom: spacing.xl, position: 'relative', zIndex: 2 }}>
        <Title 
           level="h1"
           style={{
             color: '#fff',
             fontFamily: '"Comic Sans MS", cursive, sans-serif',
             textShadow: '2px 2px 4px rgba(0,0,0,0.3)',
             marginBottom: spacing.l
           }}
         >
          🎮 小手指打字游戏 🎮
        </Title>
        
        <Space direction="horizontal" size="small" style={{ justifyContent: 'center', marginBottom: spacing.m }}>
          <Card style={scoreCardStyle}>
            <div style={{ padding: spacing.m, display: 'flex', alignItems: 'center', gap: spacing.xs }}>
              <StarIcon style={{ color: '#fff' }} />
              <Text style={{ color: '#fff', fontWeight: 'bold' }}>得分: {score}</Text>
            </div>
          </Card>
          
          <Card style={scoreCardStyle}>
            <div style={{ padding: spacing.m, display: 'flex', alignItems: 'center', gap: spacing.xs }}>
              <HeartIcon style={{ color: '#fff' }} />
              <Text style={{ color: '#fff', fontWeight: 'bold' }}>连击: {streak}</Text>
            </div>
          </Card>
          
          <Card style={scoreCardStyle}>
            <div style={{ padding: spacing.m, display: 'flex', alignItems: 'center', gap: spacing.xs }}>
              <GiftIcon style={{ color: '#fff' }} />
              <Text style={{ color: '#fff', fontWeight: 'bold' }}>等级: {level}</Text>
            </div>
          </Card>
        </Space>

        <div style={{ marginBottom: spacing.m }}>
          <Text style={{ color: '#fff', marginBottom: spacing.xs, fontSize: '18px', fontWeight: 'bold' }}>
            剩余时间: {timeLeft}秒
          </Text>
          <Progress 
            percentage={progress}
            strokeWidth={10}
            style={{ borderRadius: borderRadius.medium }}
          />
        </div>
      </div>

      <Space direction="horizontal" size="medium" style={{ justifyContent: 'center', marginBottom: spacing.xl }}>
        {!isPlaying && timeLeft > 0 ? (
          <Button
            theme="success"
            size="large"
            onClick={startGame}
            style={{
              fontSize: '1.2rem',
              padding: '12px 24px',
              borderRadius: borderRadius.large
            }}
          >
            <PlayIcon style={{ marginRight: spacing.xs }} />
            开始游戏
          </Button>
        ) : (
          <Button
            theme="warning"
            size="large"
            onClick={pauseGame}
            style={{
              fontSize: '1.2rem',
              padding: '12px 24px',
              borderRadius: borderRadius.large
            }}
          >
            <PauseIcon style={{ marginRight: spacing.xs }} />
            暂停
          </Button>
        )}
        
        <Button
          theme="danger"
          size="large"
          onClick={resetGame}
          style={{
            fontSize: '1.2rem',
            padding: '12px 24px',
            borderRadius: borderRadius.large
          }}
        >
          <RefreshIcon style={{ marginRight: spacing.xs }} />
          重新开始
        </Button>
      </Space>

      <AnimatedCharacter 
        mood={characterMood} 
        score={score}
      />

      {currentWord && (
        <>
          <div style={wordDisplayStyle}>
            {currentWord}
          </div>

          <div style={{ marginTop: spacing.l }}>
            <Input
              value={userInput}
              onChange={handleInputChange}
              placeholder="在这里输入汉字..."
              disabled={!isPlaying || timeLeft === 0}
              style={typingInputStyle}
              size="large"
            />
          </div>
        </>
      )}

      {timeLeft === 0 && (
        <div style={{ textAlign: 'center', marginTop: spacing.xl }}>
          <Title 
             level="h2"
             style={{
               color: '#fff',
               fontFamily: '"Comic Sans MS", cursive, sans-serif',
               textShadow: '2px 2px 4px rgba(0,0,0,0.5)'
             }}
           >
            🎉 游戏结束！🎉
          </Title>
          <Title 
             level="h3"
             style={{
               color: themeColors.warning,
               marginTop: spacing.m,
               fontFamily: '"Comic Sans MS", cursive, sans-serif'
             }}
           >
            最终得分: {score} 分
          </Title>
          <Text 
            style={{
              color: '#fff',
              marginTop: spacing.s,
              fontSize: '18px'
            }}
          >
            {score >= 500 ? '🌟 太棒了！你是打字小能手！' : 
             score >= 300 ? '👏 很好！继续加油！' : 
             '💪 不错的开始，多练习会更好！'}
          </Text>
        </div>
      )}

      <style>{`
        @keyframes bounce {
          0%, 20%, 60%, 100% {
            transform: translateY(0);
          }
          40% {
            transform: translateY(-10px);
          }
          80% {
            transform: translateY(-5px);
          }
        }
        
        @keyframes shake {
          0%, 100% { transform: translateX(0); }
          25% { transform: translateX(-5px); }
          75% { transform: translateX(5px); }
        }
        
        @keyframes float {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
};

export default TypingGame;